<template>
  <el-card class="mt-10">
    <!-- 事件可以不指定回调函数 -->
    <el-form @submit.prevent>
      <el-form-item label="属性名">
        <el-input
          placeholder="请输入属性名"
          class="attr-input"
          v-model="attrFormData.attrName"
        />
      </el-form-item>
      <el-form-item>
        <!-- 
          按钮的禁用效果 

          attrName有值，不禁用false
          attrName没值，禁用true
        -->
        <el-button
          type="primary"
          :icon="Plus"
          :disabled="!attrFormData.attrName"
          @click="addAttrValue"
        >
          添加属性值
        </el-button>
        <el-table :data="attrFormData.attrValueList" border class="mt-20">
          <el-table-column
            label="序号"
            type="index"
            width="60"
            align="center"
          />
          <el-table-column label="属性值名称">
            <template v-slot="{ row, $index }">
              <!-- 
                autofocus 文档中自动获取焦点属性没用

                文本  显示模式 show
                input 编辑模式 edit

                显示模式和编辑模式的切换
              -->
              <el-input
                size="small"
                ref="inputRef"
                v-model="row.valueName"
                v-if="row.isEdit"
                @blur="switchShow(row, $index)"
                @keyup.enter="handleKeyupSwitchShow(row)"
              />
              <div v-else @click="switchEdit(row)">
                {{ row.valueName }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template v-slot="{ row, $index }">
              <el-tooltip
                effect="light"
                content="删除属性值"
                placement="bottom"
              >
                <span>
                  <el-popconfirm
                    :title="`确定要删除${row.valueName}吗?`"
                    @confirm="delAttrValue($index)"
                  >
                    <template #reference>
                      <el-button type="danger" :icon="Delete" size="small" />
                    </template>
                  </el-popconfirm>
                </span>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <!-- 
          禁用效果
            1. 属性名有值 attrFormData.attrName
            2. 属性值列表中的属性值名称也要有值
              attrFormData.attrValueList.length > 0
              attrFormData.attrValueList.some(attrValue => attrValue.valueName)
         -->
        <el-button
          type="primary"
          :disabled="isBtnDisabled"
          @click="addOrUpdateAttr"
        >
          确定
        </el-button>
        <el-button @click="showAttrList">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "AddOrUpdateAttr",
};
</script>

<script lang="ts" setup>
import { reactive, ref, nextTick, computed } from "vue";
import { Plus, Delete } from "@element-plus/icons-vue";
import { useCategoryStore } from "@/stores/category";
import { useAttrStore } from "@/stores/attr";
import { saveAttrApi } from "@/api/product/attr";
import type { AttrItem, AttrValueItem } from "@/api/product/model/attrModel";
import { ElMessage } from "element-plus";

const attrStore = useAttrStore();

const attrFormData = reactive<AttrItem>({
  attrName: attrStore.attrName,
  attrValueList: attrStore.attrValueList,
});

const inputRef = ref();

// 点击添加属性值按钮
const addAttrValue = async () => {
  // 给数据添加一条数据，table渲染一行数据
  // 数据更新是同步，用户界面是异步
  attrFormData.attrValueList.push({
    valueName: "",
    isEdit: true,
  });

  // nextTick(() => {
  //   // 让input聚焦
  //   inputRef.value.focus();
  // });
  /*
    等DOM元素更新完毕，
      如果是回调函数形式，再触发回调函数
      如果是promise对象形式，promise变成成功状态

    真正理解：将函数添加异步队列去，等待将来执行
  */
  await nextTick();

  // 让input聚焦
  inputRef.value.focus();
};

// 失去焦点。变成显示模式
const switchShow = (row: AttrValueItem, index: number) => {
  row.isEdit = false;
  // 当输入内容为空时，需要删除这行数据
  if (!row.valueName) {
    attrFormData.attrValueList.splice(index, 1);
  }
};

const handleKeyupSwitchShow = (row: AttrValueItem) => {
  if (row.valueName) {
    row.isEdit = false;
  }
};

// 点击文本，变成编辑模式
const switchEdit = async (row: AttrValueItem) => {
  row.isEdit = true;
  await nextTick();
  // 让input聚焦
  inputRef.value.focus();
};

// 删除属性值
const delAttrValue = (index: number) => {
  attrFormData.attrValueList.splice(index, 1);
};

// 确定按钮的禁用效果
const isBtnDisabled = computed(() => {
  return (
    !attrFormData.attrName ||
    !attrFormData.attrValueList.some((attrValue) => attrValue.valueName)
  );
});

const categoryStore = useCategoryStore();
// 添加或修改属性
const addOrUpdateAttr = async () => {
  await saveAttrApi({
    ...attrFormData,
    categoryId: categoryStore.category3Id as number,
    categoryLevel: 3,
    // 添加id是undefined不会影响功能
    // 修改id有值，走修改
    id: attrStore.id,
  });
  showAttrList();
  ElMessage.success(`${attrStore.id ? "修改" : "添加"}属性成功`);
};

const emit = defineEmits(["setIsShowAttrList"]);

const showAttrList = () => {
  emit("setIsShowAttrList", true);
};
</script>

<style scoped>
.attr-input {
  width: 200px;
}
</style>
